﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Stock
{	public partial class ShiftOut : Form
	{	private	Util.ActionType actionType;
		private	ShiftsOut shiftsOut;
//-------------------------------------------------------------------------------------------------
		private	DIProject.DataSets.Stock shiftsOutStock{get{return shiftsOut != null? shiftsOut.stock: null;}}
		private	DIProject.DataSets.StockTableAdapters.ShiftsOutTableAdapter shiftsOutTableAdapter{get{return shiftsOut != null? shiftsOut.shiftsOutTableAdapter: null;}}
		private	DIProject.DataSets.Stock.ShiftsOutRow shiftsOutRow = null;
    private int docId
    {
        get 
        { 
            return shiftsOutRow != null ? shiftsOutRow.Id : 0; 
        }
    }
    private string docNumber
    {
        get 
        { 
            return shiftsOutRow != null ? shiftsOutRow.DocNumber : Properties.Resources.strUndefined; 
        }
    }
    private string docDate
    {
        get 
        { 
            return shiftsOutRow != null ? shiftsOutRow.DocDate.ToString("d") : Properties.Resources.strUndefined; 
        }
    }
    private decimal sum
    {
        get
        {
            object s = stock.ShiftOutLines.Compute("sum(RetailSum)", null);
            return s is decimal ? (decimal)s : 0m;
        }
    }
//-------------------------------------------------------------------------------------------------
		public ShiftOut() : this(Util.ActionType.NoAction, null)
		{
		}

		public ShiftOut(Util.ActionType actionType, ShiftsOut shiftsOut)
		{	
            InitializeComponent();
			textFormat = Text;
			this.actionType	= actionType;
			this.shiftsOut	= shiftsOut;
			toolStripButtonUpdate.Enabled = false;
			toolStripButtonDelete.Enabled = false;
			if(	actionType == DIProject.Util.ActionType.Update
			&&	shiftsOut != null
			&&	shiftsOut.shiftsOutGridView.CurrentCell != null)
				shiftsOutRow = (DIProject.DataSets.Stock.ShiftsOutRow)((DataRowView)shiftsOut.shiftsOutGridView.CurrentCell.OwningRow.DataBoundItem).Row;
		}
//-------------------------------------------------------------------------------------------------
		private readonly string textFormat;
		private void SetCaption()
		{	
            Text = string.Format
			(	textFormat
			,	docNumber
			,	docDate
			,	sum.ToString("N2")
			);
		}
//-------------------------------------------------------------------------------------------------
		private void ShiftOut_Load(object sender, EventArgs e)
		{	
            try
			{	
                departmentsTableAdapter.Fill(dictionary.Departments);
				switch(actionType)
				{	case DIProject.Util.ActionType.Insert:
						shiftsOutRow = shiftsOutStock.ShiftsOut.NewShiftsOutRow();
						shiftsOutRow.DocDate	= DateTime.Today;
						shiftsOutRow.MD			= DateTime.Now;
						shiftsOutRow.MW			= FirstForm.Login;
						shiftsOutStock.ShiftsOut.AddShiftsOutRow(shiftsOutRow);
						goto case DIProject.Util.ActionType.Update;
					case DIProject.Util.ActionType.Update:
						shiftOutLinesTableAdapter.Fill(stock.ShiftOutLines, docId);
						comboBoxDepartment.DataBindings.Add("SelectedValue", shiftsOutRow, "DepartmentId");
						textBoxNote.DataBindings.Add("Text", shiftsOutRow, "Note");
						break;
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void ShiftOut_FormClosing(object sender, FormClosingEventArgs e)
		{	BindingManagerBase bindingManager = BindingContext[shiftsOutRow];
			if(bindingManager != null)
				bindingManager.EndCurrentEdit();
			int		delLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Deleted	).Length
				,	insLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Added	).Length
				;
			if(shiftsOutRow.RowState != DataRowState.Unchanged
			|| delLines > 0
			|| insLines > 0)
				switch(MessageBox.Show
					(	this
					,	Properties.Resources.strDocIsChanged
					,	Properties.Resources.strConfirmation
					,	MessageBoxButtons.YesNoCancel
					,	MessageBoxIcon.Question
					,	MessageBoxDefaultButton.Button1
					)
				)
				{	case DialogResult.Yes:
						toolStripButtonSave_Click(toolStripButtonSave, EventArgs.Empty);
						delLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Deleted	).Length;
						insLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Added	).Length;
						if(shiftsOutRow.RowState != DataRowState.Unchanged
						|| delLines > 0
						|| insLines > 0)
							e.Cancel = true;
						break;
					case DialogResult.No:
						shiftsOutRow.RejectChanges();
						stock.ShiftOutLines.RejectChanges();
						break;
					case DialogResult.Cancel:
						e.Cancel = true;
						break;
				}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void ShiftOut_Resize(object sender, EventArgs e)
		{	int width = panelHeader.ClientSize.Width - labelDepartment.Left - comboBoxDepartment.Left;
			comboBoxDepartment.	Width = width;
			textBoxNote.		Width = width;
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{	if(clickedCell != null)
			{	updateToolStripMenuItem.Enabled = true;
				deleteToolStripMenuItem.Enabled = true;
			}
			else
			{	updateToolStripMenuItem.Enabled = false;
				deleteToolStripMenuItem.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private DataGridViewCell clickedCell = null;
		private void linesGridView_MouseDown(object sender, MouseEventArgs e)
		{	clickedCell = null;
			if(e.Button == MouseButtons.Right)
			{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
				if(hit.Type == DataGridViewHitTestType.Cell)
					linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
			}
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_CurrentCellChanged(object sender, EventArgs e)
		{	if(linesGridView.CurrentCell != null)
			{	toolStripButtonUpdate.Enabled = true;
				toolStripButtonDelete.Enabled = true;
			}
			else
			{	toolStripButtonUpdate.Enabled = false;
				toolStripButtonDelete.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void toolStripRefresh_Click(object sender, EventArgs e)
		{	try
			{	departmentsTableAdapter.Fill(dictionary.Departments);
				shiftOutLinesTableAdapter.Fill(stock.ShiftOutLines, docId);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonSave_Click(object sender, EventArgs e)
		{	
            try
			{	
                BindingManagerBase bindingManager = BindingContext[shiftsOutRow];
				if(bindingManager != null)
					bindingManager.EndCurrentEdit();
				int		delLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Deleted	).Length
					,	insLines = stock.ShiftOutLines.Select(null, null, DataViewRowState.Added	).Length
					;
				shiftsOutTableAdapter.Update(shiftsOutRow);				// Заголовок документа
				if(actionType == DIProject.Util.ActionType.Insert)
				{	
                    shiftsOut.shiftsOutGridView.CurrentCell = shiftsOut.shiftsOutGridView.Rows[shiftsOut.shiftsOutGridView.Rows.Count - 1].Cells[shiftsOut.shiftsOutGridView.CurrentCell.ColumnIndex];
					for(int i = 0, n = stock.ShiftOutLines.Rows.Count; i < n; ++i)
						stock.ShiftOutLines[i].DocId = shiftsOutRow.Id;
				}
				shiftOutLinesTableAdapter.Update(stock.ShiftOutLines);	// Строки документа
				shiftsOutRow.DepartmentName	= comboBoxDepartment.Text;
                shiftsOutRow.Lines = shiftsOutRow.Lines - delLines + insLines;
                shiftsOutRow.DocSum = sum;
				shiftsOutRow.AcceptChanges();
				stock.ShiftOutLines.AcceptChanges();
			}
			catch(SqlException eq)
			{	
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripPrint_Click(object sender, EventArgs e)
		{	
            bool changed	= shiftsOutRow.RowState != DataRowState.Unchanged
						||	DIProject.Util.Common.HasChanges(stock.ShiftOutLines)
						;
			if(changed)
			{	
                if(MessageBox.Show
				(	this
				,	Properties.Resources.strDocIsChanged
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes)
				{	try
					{	shiftOutLinesTableAdapter.Update(stock);
						changed = false;
					}
					catch(Exception ex)
					{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			if(!changed)
			{	
                ShiftOutRpt shiftOutRpt = new ShiftOutRpt(docId);
				shiftOutRpt.ShowDialog(this);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripInsert_Click(object sender, EventArgs e)
		{	
            ShiftOutLine shiftOutLine = new ShiftOutLine(Util.ActionType.Insert);
			if(shiftOutLine.ShowDialog(this) == DialogResult.OK)
			{	try
				{	DIProject.DataSets.Dictionary.PartiesRow partyRow = shiftOutLine.PartyRow;
					DIProject.DataSets.Stock.ShiftOutLinesRow newRow = stock.ShiftOutLines.NewShiftOutLinesRow();
					newRow.DocId			= docId;
					newRow.PartyId			= partyRow.Id;
					newRow.Name				= partyRow.Name;
					newRow.ManufacturerId	= partyRow.ManufacturerId;
					newRow.ManufacturerName	= partyRow.ManufacturerName;
					newRow.RetailPrice		= partyRow.RetailPrice;
					newRow.Qntty			= shiftOutLine.Qntty;
					newRow.RetailSum		= shiftOutLine.Sum;
				//?	newRow.ReturnLineId		= ;
					newRow.Note				= shiftOutLine.Note;
					newRow.MD				= DateTime.Now;
					newRow.MW				= FirstForm.Login;
					stock.ShiftOutLines.AddShiftOutLinesRow(newRow);
					linesGridView.CurrentCell = linesGridView.Rows[stock.ShiftOutLines.Count - 1].Cells[linesGridView.CurrentCell.ColumnIndex];
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripUpdate_Click(object sender, EventArgs e)
		{	
            if(linesGridView.CurrentCell != null)
			{	
                try
				{	
                    DIProject.DataSets.Stock.ShiftOutLinesRow row = (DIProject.DataSets.Stock.ShiftOutLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row;
					ShiftOutLine shiftOutLine	= new ShiftOutLine(Util.ActionType.Update);
					shiftOutLine.Party			= row.PartyId;
					shiftOutLine.Manufacturer	= row.ManufacturerName;
					shiftOutLine.Qntty			= row.Qntty;
					shiftOutLine.Price			= row.RetailPrice;
					shiftOutLine.Note			= row.Note;
					if(shiftOutLine.ShowDialog(this) == DialogResult.OK)
					{	row.Qntty		= shiftOutLine.Qntty;	// Меняются только количество
						row.RetailSum	= shiftOutLine.Sum;		//   сумма
						row.Note		= shiftOutLine.Note;	//   и примечание
						SetCaption();
					}
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripDelete_Click(object sender, EventArgs e)
		{	
            DIProject.DataSets.Stock.ShiftOutLinesRow rowToDelete;
			if(	linesGridView.CurrentCell != null
			&&	(rowToDelete = (DIProject.DataSets.Stock.ShiftOutLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row) != null
			&&	MessageBox.Show
				(	this
				,	string.Format(Properties.Resources.strDeleteDocLine, rowToDelete.Name)
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes
			)
			{	try
				{	rowToDelete.Delete();
				}
				catch(SqlException eq)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyDown(object sender, KeyEventArgs e)
		{	if(e.KeyCode == Keys.Enter)
				e.Handled = true;
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyPress(object sender, KeyPressEventArgs e)
		{	if(e.KeyChar == '\r' && linesGridView.CurrentCell != null)
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
			if(hit.Type == DataGridViewHitTestType.Cell)
			{	linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
	}
}